package com.wbb.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.wbb.constant.ResultConstants;
import com.wbb.result.JsonResult;
import com.wbb.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Order(-1)
public class LoginFilter implements GlobalFilter {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        AntPathMatcher antPathMatcher = new AntPathMatcher();

        // 准备一个容器
        String[] arr = {"/login/**"};
        // 获取当前访问路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        for (String s : arr) {
            if (antPathMatcher.match(s,path)){
                return chain.filter(exchange);
            }
        }

        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        // token无效
        if (token == null || token.isEmpty()) return getVoidMono(exchange);
        try {
            jwtUtil.parseJwt(token);
        }catch (Exception e){
            return getVoidMono(exchange);
        }

        return chain.filter(exchange);
    }

    private Mono<Void> getVoidMono(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        //设置响应头编码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        //设置响应内容
        JsonResult result = JsonResult.response(ResultConstants.TOKEN_INVALID); //code: -3
        //不输出为null的字段
        byte[] bytes = JSONObject.toJSONBytes(result, SerializerFeature.WriteMapNullValue);
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }
}
